<template>
  <el-card style="width: 100%">
    <!-- 搜索栏 -->
    <div
      style="
        margin-bottom: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
      "
    >
      <el-input
        v-model="keyword"
        placeholder="请输入用户名、邮箱、角色或子系统"
        style="width: 300px"
        clearable
        @change="onKeywordChange"
      />
      <el-button type="primary" @click="openAddDialog">新增用户</el-button>
    </div>

    <!-- 用户列表表格 -->
    <el-table
      :data="tableData"
      :height="view.height - 290"
      style="width: 100%"
      v-loading="tableLoading"
    >
      <el-table-column prop="username" label="用户名" width="220" />
      <el-table-column prop="email" label="邮箱" width="280" />
      <el-table-column prop="isActive" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.isActive ? 'success' : 'danger'">
            {{ scope.row.isActive ? "激活" : "未激活" }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 显示角色名称 -->
      <el-table-column prop="roleName" label="角色" />
      <!-- 显示子系统名称 -->
      <el-table-column prop="subsystemName" label="子系统" />
      <el-table-column prop="createDate" label="创建时间" width="220" />
      <el-table-column prop="updateDate" label="更新时间" width="220" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="openEditDialog(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="small"
            @click="deleteUser(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin-top: 20px; text-align: right">
      <el-pagination
        background
        :current-page="userPagination.page_index"
        :page-size="userPagination.page_size"
        :total="userPagination.page_total"
        layout="prev, pager, next"
        @current-change="onPageChange"
      />
    </div>

    <!-- 新增/编辑用户弹窗 -->
    <el-dialog :title="dialogTitle" v-model="isDialogVisible" width="500px">
      <el-form :model="formData" :rules="formRules" ref="userForm">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formData.username"
            :disabled="dialogTitle == '编辑用户'"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" />
        </el-form-item>
        <el-form-item
          label="密码"
          :prop="dialogTitle != '编辑用户' ? 'password' : ''"
        >
          <el-input
            v-model="formData.password"
            :placeholder="
              dialogTitle != '编辑用户' ? '密码为必填项' : '不修改则为原始密码'
            "
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-switch v-model="formData.isActive" />
        </el-form-item>
        <!-- 角色选择 -->
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="formData.roleId" placeholder="请选择角色">
            <el-option
              v-for="role in roles"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <!-- 子系统选择 -->
        <el-form-item label="子系统" prop="subsystemId">
          <el-select v-model="formData.subsystemId" placeholder="请选择子系统">
            <el-option
              v-for="subsystem in subsystems"
              :key="subsystem.id"
              :label="subsystem.name"
              :value="subsystem.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import HttpService from "@/api/api";

// 动态高度
const view = reactive({
  height: window.innerHeight,
});

// 分页配置
const userPagination = reactive({
  page_index: 1,
  page_size: 30,
  page_total: 0,
});

// 数据
const keyword = ref("");
const tableData = ref([]);
const tableLoading = ref(false);
const roles = ref([]);
const subsystems = ref([]);
const isDialogVisible = ref(false);
const dialogTitle = ref("新增用户");

// 表单数据和校验规则
const formData = reactive({
  id: null,
  username: "",
  email: "",
  password: "",
  isActive: true,
  roleId: "",
  subsystemId: "",
});

const formRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入有效的邮箱地址", trigger: "blur" },
  ],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
  subsystemId: [{ required: true, message: "请选择子系统", trigger: "change" }],
});

// 获取用户列表
const getUsers = () => {
  const params = {
    page: userPagination.page_index,
    limit: userPagination.page_size,
    search: keyword.value,
  };
  tableLoading.value = true;
  HttpService.userManage.userList(
    params,
    (res) => {
      if (res.status === 200) {
        // 通过角色 ID 和子系统 ID 映射获取名称
        tableData.value = res.data.data.map((user: any) => {
          const role = roles.value.find((role) => role.id === user.roleId);
          const subsystem = subsystems.value.find(
            (sub) => sub.id === user.subsystemId
          );
          return {
            ...user,
            roleName: role ? role.name : "未知角色",
            subsystemName: subsystem ? subsystem.name : "未知子系统",
          };
        });
        userPagination.page_total = res.data.total;
      } else {
        ElMessage.error("获取用户列表失败");
      }
      tableLoading.value = false;
    },
    (error) => {
      ElMessage.error("请求失败，请稍后重试");
      tableLoading.value = false;
    }
  );
};

// 获取角色列表
const getRoles = () => {
  const params = {
    page: userPagination.page_index,
    limit: userPagination.page_size,
    search: keyword.value, // 根据关键字搜索
  };
  tableLoading.value = true;
  HttpService.roleManage.roleList(
    params,
    (res) => {
      if (res.status === 200) {
        roles.value = res.data.data;
      } else {
        ElMessage.error("获取角色列表失败");
      }
      tableLoading.value = false;
    },
    (error) => {
      ElMessage.error("请求失败，请稍后重试");
      tableLoading.value = false;
    }
  );
};

// 获取子系统列表
const getSubsystems = () => {
  const params = {
    page: userPagination.page_index,
    limit: userPagination.page_size,
    search: keyword.value, // 根据关键字搜索
  };
  tableLoading.value = true;
  HttpService.subsystemManage.subsystemList(
    params,
    (res) => {
      if (res.status === 200) {
        subsystems.value = res.data.data;
      } else {
        ElMessage.error("获取子系统列表失败");
      }
      tableLoading.value = false;
    },
    (error) => {
      ElMessage.error("请求失败，请稍后重试");
      tableLoading.value = false;
    }
  );
};

// 分页切换
const onPageChange = (newPage: number) => {
  userPagination.page_index = newPage;
  getUsers();
};

// 搜索关键字修改事件
const onKeywordChange = () => {
  userPagination.page_index = 1;
  getUsers();
};

// 新增用户
const openAddDialog = () => {
  dialogTitle.value = "新增用户";
  formData.id = null;
  formData.username = "";
  formData.email = "";
  formData.password = "";
  formData.isActive = true;
  formData.roleId = "";
  formData.subsystemId = "";
  isDialogVisible.value = true;
};

// 编辑用户
const openEditDialog = (row: any) => {
  console.log(row);
  dialogTitle.value = "编辑用户";
  formData.id = row.id;
  formData.username = row.username;
  formData.email = row.email;
  formData.password = ""; // 编辑时密码不需要填
  formData.isActive = row.isActive;
  formData.roleId = row.roleId;
  formData.subsystemId = row.subsystemId;
  isDialogVisible.value = true;
};

// 保存用户
const saveUser = () => {
  const action = formData.id ? "updateUser" : "addUser";
  const params = { ...formData };
  if (!params.password) {
    delete params.password;
  }
  HttpService.userManage[action](
    params,
    (res) => {
      if (res.status === 200) {
        ElMessage.success(`${formData.id ? "更新" : "新增"}用户成功`);
        isDialogVisible.value = false;
        getUsers();
      } else {
        ElMessage.error(`${formData.id ? "更新" : "新增"}用户失败`);
      }
    },
    (error) => {
      ElMessage.error("操作失败，请稍后重试");
    }
  );
};

// 删除用户
const deleteUser = (id: number) => {
  HttpService.userManage.deleteUser(
    { id },
    (res) => {
      if (res.status === 200) {
        ElMessage.success("删除成功");
        getUsers();
      } else {
        ElMessage.error("删除失败");
      }
    },
    (error) => {
      ElMessage.error("删除失败，请稍后重试");
    }
  );
};

// 窗口大小监听
const updateViewHeight = () => {
  view.height = window.innerHeight;
};

window.addEventListener("resize", updateViewHeight);

onMounted(async () => {
  await getRoles();
  await getSubsystems();
  getUsers();
  updateViewHeight();
});
</script>

<style scoped>
/* 样式根据需求自定义 */
</style>
